package com.harven.maplite.complier;

import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeSpec;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.processing.Messager;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.util.Elements;

public class BindViewHandler {
    private final String bindingClassName;
    private final String packageName;
    private final TypeElement typeElement;
    private final Map<Integer, VariableElement> variableElementMap = new HashMap<>();
    private final Messager messager;

    public BindViewHandler(Elements elementUtils, TypeElement classElement, Messager messager) {
        this.typeElement = classElement;
        PackageElement packageElement = elementUtils.getPackageOf(typeElement);
        String packageName = packageElement.getQualifiedName().toString();
        String className = typeElement.getSimpleName().toString();
        this.packageName = packageName;
        this.bindingClassName = className + "_ViewBinding";
        this.messager = messager;
    }

    public void putElement(int id, VariableElement element) {
        variableElementMap.put(id, element);
    }

    public TypeSpec handleClassSpec() {
        return TypeSpec.classBuilder(bindingClassName)
                .addModifiers(Modifier.PUBLIC)
                .addMethod(appendMethod())
                .build();
    }

    private MethodSpec appendMethod() {
        ClassName host = ClassName.bestGuess(typeElement.getQualifiedName().toString());
        MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("bind")
                .addModifiers(Modifier.PUBLIC)
                .returns(void.class)
                .addParameter(host, "host");
        for (int id : variableElementMap.keySet()) {
            VariableElement element = variableElementMap.get(id);
            String varName = element.getSimpleName().toString();
            String varType = element.asType().toString();
//            messager.printMessage(Diagnostic.Kind.NOTE, String.format("id:%s %s", id, element));
//            methodBuilder.addCode("host." + varName + " = " + "(" + varType + ")(((android.app.Activity)host).findViewById( " + id + "));\r\n");
            methodBuilder.addStatement("host.$N = ($N)(((android.app.Activity)host).findViewById($L))", varName, varType, id);
        }
        return methodBuilder.build();
    }


    public String getPackageName() {
        return packageName;
    }
}
